package com.stud.system.service.impl;

import cn.hutool.core.io.FileUtil;
import com.stud.common.exception.ServiceException;
import com.stud.common.utils.file.FileUtils;
import com.stud.system.properties.FileProperties;
import com.stud.system.service.FileEngine;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 本地文件存储
 *
 * @author Stud
 * @date 2024-06-04 11:23:15
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class LocalFileServiceImpl implements FileEngine {

    private final FileProperties fileProperties;

    @Override
    public String upload(MultipartFile sourceFile, String targetFolder, String targetFileName) {
        log.info("开始往本地上传");
        String fileKey = fileProperties.getFolder() + "/" + targetFolder + "/" + targetFileName;
        try {
            FileUtil.writeFromStream(sourceFile.getInputStream(), fileKey);
        } catch (IOException e) {
            throw new ServiceException("上传到本地失败:" + e.getMessage());
        }
        return fileKey;
    }

    @Override
    public String getDownloadUrl(String fileKey) {
        //todo 暂时没时间写,Stud 2024-06-04 11:23:15
        return null;
    }

    @Override
    public void download(String fileKey, OutputStream outputStream) {
        FileUtil.writeToStream(fileKey, outputStream);
    }

    @Override
    public boolean remove(String... fileKeys) {
        if (fileKeys == null || fileKeys.length == 0) {
            return false;
        }
        for (String fileKey : fileKeys) {
            try {
                FileUtils.deleteFile(fileKey);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return true;
    }
}
